var Promise = require('bluebird');
var ObjectID = require('mongodb').ObjectID;

var mongoBase = require('../common/mongo-base');
var page = require('../common/page');

module.exports = {
  list: list,
  newsArticle: newsArticle
};

function list(req, res, next) {

  var pageNo = Math.floor(req.query.pageNo);
  var pageSize = Math.floor(req.query.pageSize);
  pageNo = pageNo ? pageNo: 1;
  pageSize = pageSize ? pageSize: 20;

  var query = {};
  var fields = {_id:1, originalLink:1, artibodyTitle:1, mediaName:1, medialink:1, photo:1, ellipsis:1, pubDate:1};
  var options = {sort:{date:-1}, skip: (pageNo - 1) * pageSize, limit:pageSize};

  Promise.all([
    mongoBase.findData('news-article', query, fields, options),
    mongoBase.countData('news-article')
  ])

  .then(function(results) {
    var resData = {
      isNews: true,
      searchType: 'news',
      newsList: results[0],
      totalCount: results[1]
    }
    /*分页数据*/
    resData.page = page.getPage(pageNo, pageSize, resData.totalCount, 7);

    res.render('news', resData);
  })

  .catch(function(err){
    console.log(err);
  });
}

function newsArticle(req, res, next) {

  var artId = req.query.artId;

  if(!artId) {
    next();
    return;
  }

  var query = {_id: new ObjectID(artId)};
  var fields = {_id:1, originalLink:1, artibodyTitle:1, mediaName:1, pubDate:1, 
    medialink:1, photo:1, artibody:1, pubDate:1, keywords:1};

  mongoBase.findOneData('news-article', query, fields)

    .then(function(data) {
      var resData = {
        isNews: true,
        searchType: 'news',
        acticle: data
      }
      res.render('article', resData);
    })

    .catch(function(err){
      console.log(err);
    });
}